//-----------------------------------------------------------------------------------
// This file prepares daily return data surrounding the implementation of margin debt
//-----------------------------------------------------------------------------------
clear

// Define vintage dates and corresponding group numbers
// First of the Month
local v2_first_0=date("02/01/2013", "MDY")
local v3_first_0= date("10/01/2013", "MDY")
local v4_first_0= date("10/01/2014", "MDY")

foreach x in 1 3 12{
	local v2_first_`x'=dofm(mofd(`v2_first_0')-`x')
	local v3_first_`x'=dofm(mofd(`v3_first_0')-`x')
	local v4_first_`x'=dofm(mofd(`v4_first_0')-`x')
}


// Loading Daily Stock Return Data
use ../dta/stock_daily.dta, clear
gen m = mofd(date)
keep if m > 600 
keep code date ret_dgtw 


// Creating Cumulative DGTW Returns at Various Horizons for Each of 3 Vintages
foreach y in 0 1 3 12{ // Baseline Month
	foreach x in 2 3 4{ // Vintage
		preserve
		keep if date >= `v`x'_first_`y'' & date <=  `v`x'_first_`y''+ 740	
		drop if ret_dgtw==.
		bys code (date): gen car_ret_dgtw = sum(ret_dgtw)
		// Creating a Balanced Panel
		tsset code date
		tsfill, full
		gen m=mofd(date)
		bys date: egen any_trading=total(car_ret_dgtw), missing 
		drop if any_trading==. // Removing non-trading days
		bys code m (date): keep if _n==_N
		bys code (m): gen months_relative_to_baseline=_n
		disp "test"
		keep if months_relative_to_baseline==1|months_relative_to_baseline==3 ///
			   |months_relative_to_baseline==12|months_relative_to_baseline==24
		gen rd_group = `x'
		gen baseline_month=`y'
		tempfile daily_`x'_`y'
		save `daily_`x'_`y''
		restore
	}
}

// Combine Returns For Each Vintage + Horizon
clear
foreach y in 0 1 3 12{
	foreach x in 2 3 4 {
		append using `daily_`x'_`y''
	}	
}

// Limit Sample to Active Vintages + Never-Marginable 
merge m:1 code using  ../dta/code_vintage_crosswalk.dta, keep(match) // Loading Event Returns
keep if vintage==rd_group|vintage==. // Eliminating Pilot Vintages
gen anyvintage=(vintage>=2 & vintage<=4) // Defining Treatment Indicator

// Saving Data
save ../dta/event_study_data.dta, replace




